#!/usr/bin/perl -w

use strict;
use warnings;
use Time::Local;

#
#  Displays the file if the modified time is in time range
#    @params
#       1) File
#       2) Min Bound Time (Unix time)
#       3) Max Bound date (Unix time)
#
sub disp_file_mtime
{
  my ($CurrentFile, $MinDate, $MaxDate) = @_;

  my ($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size,
      $atime, $mtime, $ctime, $blksize, $blocks) =
        stat($CurrentFile);

  if($MinDate <= $mtime && $MaxDate >= $mtime)
  {
    print("$CurrentFile \n");
  }
}

sub usage()
{
  print "Alternative tool for find </path/to/dir> -type f -mtime <days ago>\n";
  print "Usage:\n";
  print "  $0 \@year:int \@month:int \@date:int \@range:int \@dir:string [--print-range]\n";
  print "  $0 \@range:int \@dir:string [--print-range]\n\n";
  print "Sample:\n";
  print "  $0 2012 01 01 -1 /etc \n";
  print "    * list files from /etc with modified date from 12/31/2011 to 01/01/2012\n\n";
  print "  $0 -1 /etc \n";
  print "    * list files from /etc with modified date from ^time - 24 hours \n\n";
}



####
# main
####
my $ldate = time();
my $udate = time();
my $dir_lookup = "/tmp";
my $enable_debug = 0;
use constant DEBUG_FLAG => "--print-range";


#params if debug
if($#ARGV == 5 && ! ($ARGV[5] eq DEBUG_FLAG))
{
  usage();
  exit;
}

if($#ARGV == 2 && ! ($ARGV[2] eq DEBUG_FLAG))
{
  usage();
  exit;
}

if($#ARGV == 5 || $#ARGV == 2)
{
  $enable_debug = 1;
}


#params init
if($#ARGV == 4 || $#ARGV == 5)
{
  $dir_lookup = $ARGV[4];
         # timelocal($sec,$min,$hours,$day,$month,$year); 
  $ldate = timelocal(0, 0, 0, $ARGV[2], $ARGV[1]-1, $ARGV[0]);
  if($ARGV[3] == 0)
  {
    $udate = $ldate + ((24 * 60 * 60) - 1);
  }
  else
  {
    $udate = ($ldate + ((24 * 60 * 60) * $ARGV[3]));
    $udate = $udate + ((24 * 60 * 60) - 1);     
  }
}
elsif($#ARGV == 1 || $#ARGV == 2)
{
  $dir_lookup = $ARGV[1];
  if($ARGV[0] == 0)
  {
    $ldate = $ldate - (24 * 60 * 60);
  }
  else
  {
    $udate = (time() + ((24 * 60 * 60) * $ARGV[0]));
  }
}
else
{
  usage();
  exit;
}

if( $ldate > $udate )
{
  my $swap = $ldate;
  $ldate = $udate;
  $udate = $swap;
}



if($enable_debug == 1)
{
  print "\n";
  print "listing files from ";
  print scalar localtime($ldate);
  print " to ";
  print scalar localtime($udate);
  print "\n@ $dir_lookup\n";
  print "====================\n\n";  
}

opendir(DIR,$dir_lookup) or die $!;
while( my $file = readdir(DIR))
{
  next unless (-f "$dir_lookup/$file");
  disp_file_mtime("$dir_lookup/$file", $ldate, $udate);
}
closedir(DIR);


